<template>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      v-model:error="error"
      :finished="finished"
      :immediate-check="false"
      finished-text="没有更多了"
      error-text="请求失败，点击重试"
      @load="onLoad"
    >
      <FilmItem v-for="item in list" :key="item.filmId" :data="item" />
    </van-list>
  </van-pull-refresh>
</template>

<script lang="ts" setup>
import { getFilmList } from '@/api'
import { useCityStore } from '@/stores/city'
import FilmItem from './film-item.vue'

const props = defineProps<{
  type: 1 | 2
}>()

const { curCityId } = storeToRefs(useCityStore())

// 当前页码
const pageNum = ref(1)
// 每页显示条数
const pageSize = ref(10)

const list = ref<IFilm[]>([])
const loading = ref(false)
const error = ref(false)
const finished = ref(false)
const refreshing = ref(false)

/** 加载函数 */
async function onLoad() {
  try {
    // 加载中... PS: 手动触发该函数时，注意在请求前将 loading 设置为 true
    loading.value = true
    // 调用接口
    const { films, total } = await getFilmList({
      cityId: curCityId.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      type: props.type // 1-正在热映 2-即将上映
    })
    // 将 films 追加给 list
    list.value = pageNum.value === 1 ? films : [...list.value, ...films]

    // 数据全部加载完成
    finished.value = list.value.length >= total
    // pageNum++
    pageNum.value++
  } catch (err) {
    error.value = true
  } finally {
    // 加载状态结束
    loading.value = false
    refreshing.value = false
  }
}

/** 下拉触发的函数 */
async function onRefresh() {
  // console.log('onRefresh', refreshing.value)
  // 1. 重置数据的工作
  pageNum.value = 1
  list.value = []
  loading.value = false
  error.value = false
  finished.value = false
  // 2. 手动触发 onLoad
  onLoad()
}

/** 监听 props.type 的变化 */
watch(() => props.type, onRefresh, {
  immediate: true
})
</script>

<style scoped>
.van-pull-refresh {
  margin-top: 44px;
}
</style>
